package com.jm.web.builder;


import java.io.IOException;

import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.web.BasePage;
import com.jm.web.data.JMForm;
import com.jm.web.form.baseitem.ComboxItem;
import com.jm.web.tags.support.BaseTag;

/**
 * @author yanjie
 * combox builer
 * 2011/9/29 下午1:01:10
 */
public class ComboxBuilder extends BaseBuilder{
	protected ComboxItem combox = null ;
	
	@Override
	public void init(BaseTag tag) {
		super.init(tag);
		combox = new ComboxItem();
		combox.InitTag(tag);
		combox.setFromTag(true);//设置此控件是tag生成的
		combox.setEmptysupported(false);
		//如果相同的combox前面已将加载过，则不需要重复加载
		if(this.getBaseTag().getPage().autoDatacontainsKey(this.getBaseTag().GetExtValue("name","")))
			combox.setLoad(true);
		combox.init();
	}
	
	@Override
	public void RenderEnd() {
		StringBuilderEx sb = new StringBuilderEx();
		//註冊combobox數據
		
		JMForm form = this.getBaseTag().getPage().getUtils().getForm();
		
		if(!this.getBaseTag().getPage().autoDatacontainsKey(combox.getName())){
			try {
				this.getBaseTag().getPage().addAutoData(combox.getName());
				
				this.getOut().println("<script>");
				this.getOut().print("$P.autodata['");
				this.getOut().print(combox.getName());
				this.getOut().print("']=");
				if(StringHelper.IsNullOrEmpty(combox.getOtherdata())){
					this.getOut().print("[");
					this.getOut().print(combox.getData().toString());
					this.getOut().print("];");
				}else{
					this.getOut().print("$P.autodata['");
					this.getOut().print(combox.getOtherdata());
					this.getOut().print("'];");
				}
				this.getOut().println("</script>");
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		sb.Reset();
		
		//設置text框的值
		if(!combox.isSingle() && !this.getBaseTag().isTableTagParent()){//表格中的text value 自己搞定
			String strReqValue = "";
			try{
				if(form != null && !form.isNullOrEmpty(combox.getName()))
					strReqValue = form.gpsvs(combox.getName())[this.getBaseTag().getPage().getTagItemSize(combox.getName())-1];
				
				if(!StringHelper.IsNullOrEmpty(strReqValue)){
					sb.Append("$P.form.setcomboxtextvalue('%1$s','%2$s','%3$s');",
							StringHelper.Format("%1$s_text",combox.getId()),
							combox.getName(),
							strReqValue);
				}
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//註冊combobox
		sb.Append("\r\n $('#%1$s').combobox({%2$s});",
				StringHelper.Format("%1$s",combox.getId()),
				combox.GetExtValue("config",""));
		if(!combox.isNoButton()){
			sb.Append("$('#%1$s_dropdown')",combox.getId());
			sb.Append(".attr(\"tabIndex\", -1)");
			sb.Append(".click(function() {");
			sb.Append("try{");
			if(!combox.isSingle()){
				sb.Append("\r\nvar input = $('#%1$s');",
						StringHelper.Format("%1$s_text",combox.getId()));
			}else{
				sb.Append("\r\nvar input = $('#%1$s');",combox.getId());
			}
			sb.Append("if(!input.isactive(true)){return false;}");
			sb.Append("if (input.autocomplete(\"widget\").is(\":visible\")) {");
			sb.Append("input.autocomplete(\"close\");");
			sb.Append("return;");
			sb.Append("}");
			
			if("all".equals(combox.GetExtValue("trigger",""))){
				sb.Append("input.autocomplete(\"search\", '').focus();");
			}else{
				sb.Append("input.autocomplete(\"search\", $P.gv($(input).val())).focus();");
			}
			
			sb.Append("}catch(e){alert(e);}");
			sb.Append("});");
		}
		
		this.getBaseTag().getPage().RegisterOnReadyScript(BasePage.SCRIPTRUN_ONREADY,sb.toString());
		
//		处理combox 连跳功能
		if(combox.IsContainsKey("jumpConfig")){
			sb.Reset();
			String strConfig = StringHelper.Format("{%1$s}",combox.GetExtValue("jumpConfig","").toLowerCase());
			sb.Append("var config_%2$s = %1$s;",strConfig,combox.getId());
			sb.Append("var ajax_jump_%1$s = function(args){",combox.getId());
			sb.Append("var id = '%1$s';",combox.getId());
			sb.Append("var _val = $(this).val();if(args && args['value'])_val=args['value'];");
			sb.Append("$P.processautodata(id,null);",combox.getId());
			sb.Append("if($P.isnullorempty(_val)){$('#'+id).trigger('picked');return;}");
			
			sb.Append("var p = {};");
			sb.Append("p['action']='ajax_getAutodata';");
			sb.Append("p['params']='parentvalue';");
			sb.Append("p['parentvalue']=_val;");
			sb.Append("$.extend(p,config_%1$s);",combox.getId());
			sb.Append("if((typeof p['paramsfun']) == 'function'){p['paramsfun'].call(null,p);delete p['paramsfun'];}");
			
			sb.Append("var doaction = function(jo){");
				sb.Append("if(jo != undefined && jo.ret == 1 && jo.data){");
				sb.Append("$P.processautodata(id,jo.data['autodata']);$('#'+id).trigger('picked');",combox.getId());
				sb.Append("};");
			sb.Append("};");
			sb.Append("$P.ajax({data : p,succ :doaction,url:'"+this.getBaseTag().getPage().getContextPath()+"/include/commonajax_backend.jsp'});");
			sb.Append("};");
			
			sb.Append("var xtype = config_%1$s['xtype'];",combox.getId());
			sb.Append("var parentid = config_%1$s.parentid;",combox.getId());
			sb.Append("var parentel = $('#'+parentid);",combox.getId());
			sb.Append("if(parentel.gv('xtype') != '') xtype=parentel.gv('xtype');");
			
			sb.Append("if('org' == xtype){");
				sb.Append("parentel.bind('picked',ajax_jump_%1$s);",combox.getId());
			sb.Append("}else if('combobox' == xtype || 'combobox_text' == xtype){");
				sb.Append("parentel.bind('picked',ajax_jump_%1$s);",combox.getId());
				sb.Append("parentel.bind('change',function(){if($(this).val().trim() == ''){$('#'+config_%1$s.parentid).trigger('picked',this);}});",combox.getId());
			sb.Append("}else if('multiselect' == xtype){");
				sb.Append("parentel.bind('picked',ajax_jump_%1$s);",combox.getId());
			sb.Append("}else if('text' == xtype){");
				sb.Append("parentel.blur(ajax_jump_%1$s);",combox.getId());
			sb.Append("}else{");
				sb.Append("parentel.change(ajax_jump_%1$s);",combox.getId());
			sb.Append("}");
			
			this.getBaseTag().getPage().RegisterOnReadyScript(BasePage.SCRIPTRUN_ONREADY,sb.toString());
			combox.RemoveExtValue("jumpConfig");
		}
		
		combox.RemoveExtValue("textconfig");
		combox.RemoveExtValue("valueconfig");
		combox.onRender2(this.getOut());
	}
}
